package com.haixiaoke.saas.workOrder.state.role;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.constant.WorkOrderConstants;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.house.domain.House;
import com.haixiaoke.saas.house.domain.HousePicture;
import com.haixiaoke.saas.setSwitch.domain.SetSwitch;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.workOrder.domain.*;
import com.haixiaoke.saas.workOrder.state.server.IWorkOrderTypeServerRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 看房单业务服务
 *
 * @author panda
 * @Date 2024/10/11
 **/
public class IntermediaryWorkOrderTypeServerRole extends AbstractSpecificWorkOrderTypeServerRole {
    public IntermediaryWorkOrderTypeServerRole(IWorkOrderTypeServerRole workOrderTypeServerRole) {
        super(workOrderTypeServerRole);
    }

    @Override
    @Transactional
    public int insertWorkOrder(WorkOrder workOrder, String phone) {
        String workOrderId = workOrder.getWorkOrderId();
        Date nowDate = DateUtils.getNowDate();

        //获取c端用户的id
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(workOrder.getContactsPhone());
        if (ObjectUtil.isEmpty(userConsumer)) {
            userConsumer = new UserConsumer();
            userConsumer.setUserMobile(workOrder.getContactsPhone());
            userConsumer.setUserName(workOrder.getContactsName());
            userConsumer.setLesseeFlag(UserConstants.LESSEE_FLAG_NO);
            userConsumer.setCreateBy(workOrder.getCreateBy());
            userConsumer.setCreateTime(nowDate);
            userConsumerService.insertUserConsumer(userConsumer);
        }

        SetSwitch setSwitch = setSwitchService.selectSetSwitchByTenantId(workOrder.getTenantId());
        if (ObjectUtil.isEmpty(setSwitch)) {
            throw new ServiceException("当前租户看房审核数据异常");
        }

        String recordContent = "";

        if (StrUtil.equals(setSwitch.getWoLookHouseCreate(), SetSwitch.AUDITING_STATE_OFF)) {
            if (StrUtil.isNotBlank(workOrder.getExpectPersonTenantId()) && workOrder.getExpectBusUserId() != null) {
                WorkOrderPerson workOrderPerson = workOrderPersonService.selectWorkOrderPersonByBusUserId(workOrder.getExpectBusUserId(),
                        workOrder.getExpectPersonTenantId());
                if (ObjectUtil.isEmpty(workOrderPerson)) {
                    throw new ServiceException("带看员不存在");
                }
                workOrder.setPersonName(workOrderPerson.getWorkOrderPersonName());
                workOrder.setExpectPersonName(workOrderPerson.getWorkOrderPersonName());
                workOrder.setPersonPhone(workOrderPerson.getWorkOrderPersonPhone());
                workOrder.setBusUserId(workOrderPerson.getBusUserId());
                workOrder.setPersonTenantId(workOrderPerson.getTenantId());
                recordContent = workOrder.getCreateBy() + "(" + phone + ")" + "提交了看房申请，自动派单给带看员：" +
                        workOrderPerson.getWorkOrderPersonName() + "(" + workOrderPerson.getWorkOrderPersonPhone() + ")";
            } else {
                House house = houseService.selectHouseById(workOrder.getHouseId());
                workOrder.setPersonName(house.getHouseManagerName());
                workOrder.setPersonPhone(house.getHouseManagerPhone());
                workOrder.setBusUserId(house.getHouseManagerId());
                workOrder.setPersonTenantId(house.getTenantId());
                recordContent = workOrder.getCreateBy() + "(" + phone + ")" + "提交了看房申请，自动派单给房管家：" +
                        house.getHouseManagerName() + "(" + house.getHouseManagerPhone() + ")";
            }
            workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING);
        } else if (StrUtil.equals(setSwitch.getWoLookHouseCreate(), SetSwitch.AUDITING_STATE_ON)) {
            workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_DISPATCH);
            recordContent = workOrder.getCreateBy() + "(" + phone + ")" + "提交了看房申请";
        }

        //插入跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord(workOrderId, WorkOrderConstants.RECORD_TYPE_USER_VISIBLE,
                WorkOrderConstants.DISPLAY_TYPE_ORDER_GENERATED, recordContent, null, null, nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        //插入工单
        workOrder.setConUserId(userConsumer.getUserId());
        workOrder.setCreateTime(nowDate);
        return workOrderService.insertWorkOrder(workOrder);
    }

    @Override
    public int rejectWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, String userName, String flatUserName) {
        if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_IN_DISPOSE, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_PAY, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_COMPLETED, workOrder.getWorkOrderState()) ||
                StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_CANCELED, workOrder.getWorkOrderState())) {
            throw new ServiceException("工单状态不正确，无法取消");
        }

        Date nowDate = DateUtils.getNowDate();
        String recordContent;
        if (StrUtil.isBlank(userName)) {
            recordContent = flatUserName;
        } else {
            recordContent = userName;
        }
        workOrderRecord.setRecordContent(recordContent + "取消了看房申请，备注：" + workOrderRecord.getRecordContent());
        workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_CANCELLED);
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_CANCELED);
        workOrder.setUpdateTime(nowDate);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int dispatchWorkOrder(WorkOrder workOrder, WorkOrderPerson workOrderPerson) {
        if (workOrder.getExpectBusUserId() == null) {
            throw new ServiceException("房管家工单不能改派");
        }

        if (!StrUtil.equals(WorkOrderConstants.WORK_ORDER_TYPE_INTERMEDIARY, workOrder.getWorkOrderType())) {
            throw new ServiceException("选择的工单人员不属于带看员");
        }

        Date nowDate = DateUtils.getNowDate();

        //工单为待派单则插入派单类型的跟进记录,如果为改派则插入没有类型的跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord();
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        workOrderRecord.setReceiverUser(workOrderPerson.getWorkOrderPersonName());
        workOrderRecord.setCreateTime(nowDate);
        if (StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_DISPATCH, workOrder.getWorkOrderState())) {
            workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
            workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_WAITING_FOR_ACCEPTANCE);
            workOrderRecord.setRecordContent(workOrder.getUpdateBy() + "指派工单给师傅 " + workOrderPerson.getWorkOrderPersonName() +
                    "(" + workOrderPerson.getWorkOrderPersonPhone() + ")");
        } else {
            workOrderRecord.setRecordContent(workOrder.getUpdateBy() + "改派工单给师傅 " + workOrderPerson.getWorkOrderPersonName() +
                    "(" + workOrderPerson.getWorkOrderPersonPhone() + ")");
        }
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setPersonName(workOrderPerson.getWorkOrderPersonName());
        workOrder.setPersonPhone(workOrderPerson.getWorkOrderPersonPhone());
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    @Transactional
    public int receivedWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能接自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能接当前机构的工单");
        }

        Date nowDate = DateUtils.getNowDate();

        WorkOrderRecord wor = new WorkOrderRecord();
        wor.setWorkOrderId(workOrder.getWorkOrderId());
        wor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        wor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_ACCEPTED);
        wor.setReceiverUser(workOrder.getPersonName());
        String recordContent = "师傅" + workOrder.getPersonName() + "已接单";
        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        wor.setRecordContent(recordContent);
        wor.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(wor);

        // 更新工单人员接单时间
        workOrderPersonService.updateWorkOrderPersonLatestOrderTime(personTenantId, busUserId);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        //接单时间
        workOrder.setReceiveOrderTime(nowDate);
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_RECEIVED);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int requestRejectionWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        //待接单以外的工单不能申请拒接
        if (!StrUtil.equals(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING, workOrder.getWorkOrderState())) {
            throw new ServiceException("工单状态不正确，无法申请拒接、作废");
        }

        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能操作自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能操作当前机构的工单");
        }
        Date nowDate = DateUtils.getNowDate();

        String workOrderState;
        String recordContent;
        WorkOrderPerson workOrderPerson = workOrderPersonService.selectWorkOrderPersonByBusUserId(busUserId, personTenantId);
        if (ObjectUtil.isEmpty(workOrderPerson)) {
            //房管家角色申请拒接
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_CANCELED;
            recordContent = "师傅" + workOrder.getPersonName() + "(" + workOrder.getPersonPhone() + ") " +
                    "发起拒接，备注：" + workOrderRecord.getRecordContent();
            workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
            workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_CANCELLED);
        } else {
            //带看员角色申请拒接
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_WAIT_AUDIT;
            recordContent = "师傅" + workOrder.getPersonName() + "(" + workOrder.getPersonPhone() + ") " +
                    "发起拒接申请，备注：" + workOrderRecord.getRecordContent();
        }

        //插入拒单跟进记录
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        workOrderRecord.setRecordContent(recordContent);
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(workOrderState);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int auditDenialWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, String username) {
        Date nowDate = DateUtils.getNowDate();

        WorkOrderRecord wor = new WorkOrderRecord();
        wor.setWorkOrderId(workOrder.getWorkOrderId());
        wor.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        wor.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_CANCELLED);
        wor.setReceiverUser(workOrder.getPersonName());

        String workOrderState = null;
        String recordContent = "";
        if (StrUtil.equals(workOrderRecord.getAuditDenial(), "1")) {
            workOrderState = WorkOrderConstants.WORK_ORDER_STATE_CANCELED;
            recordContent = username + "同意了拒接申请";
        } else if (StrUtil.equals(workOrderRecord.getAuditDenial(), "0")) {
            if (workOrder.getReceiveOrderTime() == null) {
                workOrderState = WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING;
            } else {
                workOrderState = WorkOrderConstants.WORK_ORDER_STATE_RECEIVED;

            }
            recordContent = username + "不同意拒接申请";
        }

        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        wor.setRecordContent(recordContent);
        wor.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(wor);

        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(workOrderState);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public int revocationRejectionWorkOrder(WorkOrder workOrder, WorkOrderRecord workOrderRecord, Long busUserId, String personTenantId) {
        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能操作自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能操作当前机构的工单");
        }
        Date nowDate = DateUtils.getNowDate();

        //插入拒单跟进记录
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        String recordContent = "师傅" + workOrder.getPersonName() + "（" + workOrder.getPersonPhone() + "）撤销拒接申请";
        if (StrUtil.isNotBlank(workOrderRecord.getRecordContent())) {
            recordContent = recordContent + "，备注：" + workOrderRecord.getRecordContent();
        }
        workOrderRecord.setRecordContent(recordContent);
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        //更新工单状态
        workOrder.setUpdateTime(nowDate);
        //接单时间
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_WAIT_RECEIVING);
        return workOrderService.updateWorkOrder(workOrder);
    }

    @Override
    public void applyTemporaryPassword(WorkOrder workOrder, String name, String phone, Long userId) {
        Date nowDate = DateUtils.getNowDate();
        WorkOrderPwdRecord workOrderPwdRecord = new WorkOrderPwdRecord();
        workOrderPwdRecord.setWorkOrderId(workOrder.getWorkOrderId());
        workOrderPwdRecord.setWorkOrderType(workOrder.getWorkOrderType());
        workOrderPwdRecord.setHouseId(workOrder.getHouseId());
        workOrderPwdRecord.setPremisesAddress(workOrder.getPremisesAddress());
        workOrderPwdRecord.setReqUserId(userId);
        workOrderPwdRecord.setReqUserName(name);
        workOrderPwdRecord.setReqPhone(phone);
        workOrderPwdRecord.setTenantId(workOrder.getTenantId());

        // 不需要审核直接通过发送临时密码
        SetSwitch setSwitch = setSwitchService.selectSetSwitchByTenantId(workOrder.getTenantId());
        if (StrUtil.equals(SetSwitch.AUDITING_STATE_OFF, setSwitch.getWoLookHouseReqPwd())) {
            // 密码有效期120分钟
            workOrderPwdRecord.setPwdStartTime(nowDate);
            workOrderPwdRecord.setPwdEndTime(DateUtil.offset(nowDate, DateField.MINUTE, 120));
            workOrderPwdRecord.setPwdAuditState(WorkOrderConstants.WORK_ORDER_TEMP_PASSWORD_AUDIT_STATUS_AGREE);

            // 发送临时密码
            houseLockService.workOrderAuthPwd(workOrderPwdRecord);
            workOrderPwdRecord.setRemark("系统审核通过");
            workOrderPwdRecord.setUpdateTime(nowDate);

        }

        workOrderPwdRecordService.insertWorkOrderPwdRecord(workOrderPwdRecord);
    }

    @Override
    public int updateWorkOrder(WorkOrder workOrder, String phone) {
        Date nowDate = DateUtils.getNowDate();

        // 获取c端用户的id
        UserConsumer userConsumer = userConsumerService.selectUserConsumerByMobile(workOrder.getContactsPhone());
        if (ObjectUtil.isEmpty(userConsumer)) {
            userConsumer = new UserConsumer();
            userConsumer.setUserMobile(workOrder.getContactsPhone());
            userConsumer.setUserName(workOrder.getContactsName());
            userConsumer.setLesseeFlag(UserConstants.LESSEE_FLAG_NO);
            userConsumer.setCreateBy(workOrder.getUpdateBy());
            userConsumer.setCreateTime(nowDate);
            userConsumerService.insertUserConsumer(userConsumer);
        }

        if (StrUtil.isNotBlank(workOrder.getExpectPersonTenantId()) && workOrder.getExpectBusUserId() != null) {
            WorkOrderPerson workOrderPerson = workOrderPersonService.selectWorkOrderPersonByBusUserId(workOrder.getExpectBusUserId(),
                    workOrder.getExpectPersonTenantId());
            if (ObjectUtil.isEmpty(workOrderPerson)) {
                throw new ServiceException("带看员不存在");
            }
            workOrder.setPersonName(workOrderPerson.getWorkOrderPersonName());
            workOrder.setExpectPersonName(workOrderPerson.getWorkOrderPersonName());
            workOrder.setPersonPhone(workOrderPerson.getWorkOrderPersonPhone());
            workOrder.setBusUserId(workOrderPerson.getBusUserId());
            workOrder.setPersonTenantId(workOrderPerson.getTenantId());
        } else {
            House house = houseService.selectHouseById(workOrder.getHouseId());
            workOrder.setPersonName(house.getHouseManagerName());
            workOrder.setExpectPersonName(null);
            workOrder.setPersonPhone(house.getHouseManagerPhone());
            workOrder.setBusUserId(house.getHouseManagerId());
            workOrder.setPersonTenantId(house.getTenantId());
        }


        // 插入跟进记录
        WorkOrderRecord workOrderRecord = new WorkOrderRecord(workOrder.getWorkOrderId(), WorkOrderConstants.RECORD_TYPE_USER_VISIBLE,
                WorkOrderConstants.DISPLAY_TYPE_ORDER_MODIFIED, workOrder.getContactsName() + "(" + phone
                + ")" + "修改了看房申请", null, null, nowDate);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);

        // 编辑工单
        workOrder.setConUserId(userConsumer.getUserId());
        workOrder.setUpdateTime(nowDate);
        return workOrderService.editWorkOrder(workOrder);
    }

    @Override
    public int confirmLookHouse(WorkOrder workOrder, Long busUserId, String personTenantId) {
        if (!workOrder.getBusUserId().equals(busUserId)) {
            throw new ServiceException("非法操作，只能操作自己的工单");
        }
        if (!StrUtil.equals(workOrder.getPersonTenantId(), personTenantId)) {
            throw new ServiceException("非法操作，只能操作当前机构的工单");
        }

        Date nowDate = DateUtils.getNowDate();

        String attendantPictureStr = StringUtils.join(workOrder.getAttendantPictureList(), ",");

        WorkOrderRecord workOrderRecord = new WorkOrderRecord();
        workOrderRecord.setWorkOrderId(workOrder.getWorkOrderId());
        workOrderRecord.setRecordType(WorkOrderConstants.RECORD_TYPE_USER_VISIBLE);
        workOrderRecord.setUserDisplayType(WorkOrderConstants.DISPLAY_TYPE_ORDER_COMPLETED);
        workOrderRecord.setReceiverUser(workOrder.getPersonName());
        workOrderRecord.setRecordContent("师傅" + workOrder.getPersonName() + "确认已看房");
        workOrderRecord.setCreateTime(nowDate);
        workOrderRecord.setRecordImg(attendantPictureStr);
        workOrderRecordService.insertWorkOrderRecord(workOrderRecord);


        // 插入房屋相册记录
        // 生成分组编号
        String packetIdentification = RandomUtil.randomStringWithoutStr(10, "0123456789");
        HousePicture housePicture = new HousePicture(workOrder.getHouseId(), workOrder.getPremisesAddress(), HouseConstants.HOUSE_PICTURE_ATTENDANT, workOrder.getUpdateBy(),
                workOrder.getOperatorId(), workOrder.getAttendantPictureList().size(), attendantPictureStr, workOrder.getTenantId(),
                "看房图片", null, workOrder.getWorkOrderId(), packetIdentification);
        housePictureService.insertHousePicture(housePicture);

        //更新工单
        workOrder.setUpdateTime(nowDate);
        workOrder.setWorkOrderState(WorkOrderConstants.WORK_ORDER_STATE_COMPLETED);
        workOrder.setWorkCompletedTime(nowDate);
        workOrder.setAttendantPicture(attendantPictureStr);
        return workOrderService.updateWorkOrder(workOrder);
    }
}
